﻿/// <reference path="jquery-1.8.2.js"/>
/// <reference path="../Lang/widget-nl.js"/>

// Styling of presence item
function presenceStyling(settings, presenceSubscription, presenceitem, isDialogMode) {

    configureChat(presenceitem);
    if (typeof isDialogMode == 'undefined' || isDialogMode == false)
        configureHover(presenceitem);

    //Build Chat popup link                        
    presenceitem.find('.chatbutton').unbind('click').click(function () {
        var canChat = $.trim(presenceitem.find(".canChat").html());
        if (canChat == "true") {
            var employeeSip = $.trim(presenceitem.find(".sip").html());
            var employeeName = $.trim(presenceitem.find(".name").html());
            window.open('chat.htm?employeeSip=' + employeeSip + '&employeeName=' + employeeName, "", 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no');
        }
    });

    var correctStatus = presenceitem.find('.unknown').length == 0;
    var statusOffline = presenceitem.find('.offline').length > 0;
    var statusAway = presenceitem.find('.away').length > 0;
    var statusImage = presenceitem.find('.statusImage');

    var defaultUnknownImageHref = settings.statusImageBaseUrl + "unknown.jpg";

    //update an img.statusImage element if the image changed
    if (correctStatus && settings.statusImageBaseUrl != '') {

        //build the new status image url
        var statusFileName = getFilename(presenceSubscription.Status);
        var isUpdating = presenceSubscription.Status == "Updating";

        var statusImageHref = defaultUnknownImageHref;

        if (presenceSubscription.Email != null && presenceSubscription.Email != '') {
            statusImageHref = settings.statusImageBaseUrl + presenceSubscription.Email + "/" + statusFileName + settings.statusImageExtension;
        }

        var defaultAvailableImageHref = settings.statusImageBaseUrl + presenceSubscription.Email + "/" + "default" + settings.statusImageExtension;

        // get the current status image url
        var currentStatusImageHref = statusImage.attr("src");

        if (currentStatusImageHref != statusImageHref
            && !endsWith(currentStatusImageHref, "unknown.jpg")
            && !endsWith(currentStatusImageHref, "default" + settings.statusImageExtension)) { //if they differ, update..
            if (isUpdating && statusImageHref == defaultUnknownImageHref) {
                // if status is 'Updating' and before the image was set then do not update it.
            } else {
                var browserVersion = parseInt($.browser.version, 10); //get the browser version
                $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
                // ToDo: test this in ie 7 - 8, not sure if animation would work there

                //if we run >ie8 or a decent browser, update the photo with a fancy animation
                //don't use an animation if the previous picture is unknown.jpg, to avoid a hide/show loop for missing pictures
                //chrome is a special case - when the animation is enabled the setInterval function doesn't work - also it doesn't throw any error
                if (($.browser.msie && browserVersion < 8) || $.browser.chrome || endsWith(currentStatusImageHref, "unknown.jpg") || endsWith(currentStatusImageHref, "default" + settings.statusImageExtension)) {
                    statusImage.attr("src", statusImageHref).show();
                }
                else {
                    statusImage.stop().animate({ opacity: '0' }, function() {
                        statusImage.show().attr('src', statusImageHref);
                    }).load(function() {

                        var op = 1;
                        if (statusOffline || statusAway) {
                            op = 0.5;
                        }

                        statusImage.stop().animate({ opacity: op });
                    });
                }
            }

            var retryCount = 0;
            //if a status image fails to load, show the unknown one instead
            presenceitem.find('.statusImage').error(function () {
                if (retryCount < 2) {
                    if (statusImage.attr("src") == defaultAvailableImageHref) {
                        $(this).stop().attr("src", defaultUnknownImageHref).show();
                    } else {
                        $(this).stop().attr("src", defaultAvailableImageHref).show();
                    }
                }
                retryCount++;
            });
        }


        //Build mail link
        configureEmail(presenceitem);

        //Build phone hover
        configurePhone(presenceitem);

        // configure more info link
        moreInfoLink(presenceitem);

        // localize texts
        localize(presenceitem);
    }

// Styling of presence item
    function groupPresenceStyling(settings, groupSubscription, presenceitem, isDialogMode) {

        configureChat(presenceitem);
        if (isDialogMode == false)
            configureHover(presenceitem);

        if (settings.statusImageBaseUrl != '') {

            //update an img.statusImage element if the image changed
            var statusImage = presenceitem.find('.statusImage');

            //build the new status image url                    
            var statusImageHref = settings.statusImageBaseUrl + "/Group.jpg";

            // get the current status image url
            var currentStatusImageHref = statusImage.attr("src");

            if (currentStatusImageHref != statusImageHref) { //if they differ, update..

                var browserVersion = parseInt($.browser.version, 10); //get the browser version
                $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
                // ToDo: test this in ie 7 - 8, not sure if animation would work there

                //if we run >ie8 or a decent browser, update the photo with a fancy animation
                //don't use an animation if the previous picture is unknown.jpg, to avoid a hide/show loop for missing pictures
                //chrome is a special case - when the animation is enabled the setInterval function doesn't work - also it doesn't throw any error
                if (($.browser.msie && browserVersion < 8) || $.browser.chrome || endsWith(currentStatusImageHref, "unknown.jpg") || endsWith(currentStatusImageHref, "default" + settings.statusImageExtension)) {
                    statusImage.attr("src", statusImageHref).show();
                }
                else {
                    statusImage.stop().animate({ opacity: '0' }, function () {
                        statusImage.show().attr('src', statusImageHref);
                    }).load(function () {
                        statusImage.stop().animate({ opacity: '1' });
                    });
                }
            }
        }

        //Build Chat popup link
        presenceitem.find('.chatbutton').unbind('click').click(function () {
            var canChat = $.trim(presenceitem.find(".canChat").html());
            if (canChat == "true") {
                window.open('groupchat.htm?groupId=' + groupSubscription.GroupId, "", 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no');
            }
        });

        //Build mail link
        configureEmail(presenceitem);

        //Build phone hover
        configurePhone(presenceitem);

        // configure more info link
        moreInfoLink(presenceitem);

        // localize texts
        localize(presenceitem);
    }


    function configureHover(presenceitem) {

        //hover animation
        presenceitem.hoverIntent({
            over: function () {
                $(this).css("height", 75);
                $(this).find(".buttons").show();
            },
            out: function () {
                $(this).css("height", 55);
                $(this).find(".buttons").hide();
            },
            timeout: 500
        });
    }


// Build phone hover
    function configurePhone(presenceitem) {

        var zindex = presenceitem.css("z-index");
        if (zindex == "auto") {
            zindex = 1000;
        } else {
            zindex = 1000 + zindex;
        }

        presenceitem.find(".phonebutton,.phonetooltip").css("z-index", zindex);

        presenceitem.find(".phonebutton,.phonetooltip").hover(
            function () {
                showPhoneTooltip($(this).parents(".presenceitem"));
            },
            function () {
                var tooltip = $(this).parents(".presenceitem").find(".phonetooltip");
                tooltip.hide();
            });
    }

//Build mail link
    function configureEmail(presenceitem) {
        var employeeEmail = $.trim(presenceitem.find(".email").html());
        if (employeeEmail != '') {

            var emailbutton = presenceitem.find(".emailbutton");

            emailbutton.unbind('click').click(function () {
                window.location.href = "mailto:" + employeeEmail;
            });
        }
    }


// enable chat button
    function configureChat(presenceitem) {
        var canChat = $.trim(presenceitem.find(".canChat").html());
        if (canChat == "true") {
            presenceitem.find(".chatbutton").removeClass("disabled").addClass("enabled");

            presenceitem.find(".chatbutton,.chattooltip").hover(
                function () {
                    var tooltip = $(this).parents(".presenceitem").find(".chattooltip");
                    tooltip.show();
                },
                function () {
                    var tooltip = $(this).parents(".presenceitem").find(".chattooltip");
                    tooltip.hide();
                });

        } else {
            presenceitem.find(".chatbutton").removeClass("enabled").addClass("disabled");
        }
    }

/// show email info
    function showEmailTooltip(presenceitem) {

        var tooltip = presenceitem.find(".emailtooltip");
        tooltip.show();

        // hide/show phone number div if empty
        tooltip.find(".email").each(function () {
            var container = $(this).parents(".emailContainer");
            if ($(this).html() == "") {
                container.hide();
            }
            else {
                container.show();
            }
        });
    }

/// show phone info
    function showPhoneTooltip(presenceitem) {

        var tooltip = presenceitem.find(".phonetooltip");
        var hasPhone = false;

        // hide/show phone number div if empty
        tooltip.find(".mobile,.phone").each(function () {
            var container = $(this).parents(".phoneContainer");
            if ($(this).html() == "") {
                container.hide();
            }
            else {
                container.show();
                hasPhone = true;
            }
        });

        if (hasPhone) {
            tooltip.show();
            //remove last dashed border
            presenceitem.find(".phoneContainer[display!='none']").last().css("border-bottom", "0px");
        }

    }

// show or hide more info link
    function moreInfoLink(presenceitem) {
        //convert phone numbers to E.164 Telephone URI's to make them openable trough lync
        //but only if they aren't altered by skype, otherwise clicking them opens both plugins.
        var phone = presenceitem.find('.phone:not(:has(.skype_pnh_print_container))');
        var info = presenceitem.find('.info');
        var number = phone.html();

        if ($.trim(number) != '') {
            phone.html("<a href='tel:" + number + "'>" + number + "</a>");
            var infolink = info.find('.infolink');
            var uid = number.substring(number.length - 3);
            infolink.html("<a href='http://info.orbitone.com/lync?nr=" + uid + "'>" + infolink.html() + "</a>");
        } else {
            info.hide();
        }
    }

// localize presence
    function localize(presenceitem) {
        if (typeof emailbuttonResource != 'undefined')
            presenceitem.find('.emailbutton').attr('title', emailbuttonResource.title);
        if (typeof chatbuttonResource != 'undefined')
            presenceitem.find('.chatbutton').attr('title', chatbuttonResource.title);
        if (typeof workphonedescriptionResource != 'undefined')
            presenceitem.find('.phone').parents(".phoneContainer").find(".phonedescription").html(workphonedescriptionResource.html);
        if (typeof mobilephonedescriptionResource != 'undefined')
            presenceitem.find('.mobile').parents(".phoneContainer").find(".phonedescription").html(mobilephonedescriptionResource.html);
        if (typeof chatinfoResource != 'undefined')
            presenceitem.find('.chatinfo').html(chatinfoResource.html);
        if (typeof chatLabelResource != 'undefined')
            presenceitem.find('.chatlabel').html(chatLabelResource.html);
        if (typeof phoneLabelResource != 'undefined')
            presenceitem.find('.phonelabel ').html(phoneLabelResource.html);
        if (typeof emailLabelResource != 'undefined')
            presenceitem.find('.emaillabel').html(emailLabelResource.html);
    }

// converts status to photo filename
    function getFilename(a) {
        switch (a) {
        case "Do Not Disturb": return "dnd"; 
        case "Online": return "available";
        case "Available": return "available";
        case "Offline": return "away";
        case "Away": return "Away";
        case "Updating": return "available";
        case "In a meeting": return "meeting";
        case "Busy": return "busy";
        case "On the phone": return "phone";
        case "Be Right Back": return "away";
        case "In a conference call": return "phone";
        case "Unavailable": return "away";
        default: return a;
        }
    }

    function endsWith(text, value) {
        if (text == undefined) return false;
        return (text.match(value + "$") == value);
    }
}

